package com.warrior.main;


import java.util.ArrayList;
import java.util.List;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.androidWarrior.R;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;
import com.warrior.bluetooth.BluetoothHandler;
import com.warrior.bluetooth.Sync.ISyncStateChanged;

public class MainActivity extends MyActivity 
	implements OnItemClickListener, ISyncStateChanged{

	private Button butBT,butScan;
	private ListView lv;
	private TextView tvUserName;
	private BluetoothHandler bt;
	private ArrayAdapter<String> devicesNamesAdapter;
	private List<BluetoothDevice>devicesList;
	
	private MyApp app;
	private ProfilePictureView myProfilePicture;
	private ProfilePictureView competitorProfilePicture;
	private com.facebook.widget.LoginButton butLogin;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        app = (MyApp)getApplication();
        
        devicesNamesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        devicesList = new ArrayList<BluetoothDevice>();
        
        buildViewReferences();
        buildViewListeners();  
	    
        app.buildBluetoothHandler();
        bt = app.getBluetoothHandler();
        bt.registerBluetoothDeviceFound(ReceiverScanDeviceBluetooth);
        bt.registerBluetoothDiscoveryStart(ReceiverScanDeviceBluetooth);
        bt.registerBluetoothDiscoveryFinished(ReceiverScanDeviceBluetooth);
        
    }
    
    protected void onResume() {
    	super.onResume();
    	if(bt.isEnabled()){
    		setButtonsWhenBtEnabled();
        }
    	else{
    		setButtonsWhenBtDisabled();
    	}
    	if(app.getFacebook().isOpenedConnection()){
    		app.getFacebook().openedsesions();
    	}
    }
   
    private void buildViewReferences(){
    	butBT = (Button)findViewById(R.id.butBT);
        butScan = (Button)findViewById(R.id.butScan);
        tvUserName = (TextView)findViewById(R.id.tvUserName);
        lv = (ListView)findViewById(R.id.lv);
        lv.setEmptyView((TextView)findViewById(R.id.tvEmpty));
        myProfilePicture = (ProfilePictureView)findViewById(R.id.profilePictureView);
        competitorProfilePicture = (ProfilePictureView)findViewById(R.id.competitorProfilePictureView);
        butLogin = (LoginButton)findViewById(R.id.butLogin);
    }
    private void buildViewListeners(){
    	lv.setOnItemClickListener(this);
        butBT.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!bt.isEnabled()){
					bt.setEnable();
				}	
				else {
					bt.setDisable();
				}
			}
		});
        butScan.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// the bluetooth is start scanning 
				devicesNamesAdapter.clear();
				bt.startScanning();
			}
		});
        butLogin.setSessionStatusCallback(app.getFacebook());
    }
   
	// this is turn on the client side
	public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
		try {
			app.setServer(false);
			// this is client side we need close a server
			app.killServer();
			// try to connect to server in new thread 
			// we need to pass to client the device we want to connect
			BluetoothDevice btDevice = devicesList.get(position);
			bt.createClient().connectToServer(btDevice);
			devicesNamesAdapter.clear();

		} catch (Exception e) {
			showToast(e.getMessage());
			Log.d(MyLog.MAIN_ACTIVITY,"excetion: " + e.getMessage());
		}
	}
	@Override
	public void onBackPressed() {
		//unregisterReceiver(ReceiverScanDeviceBluetooth);
		app.unregisterBluetooth();
		app.getFacebook().closeSession();
		bt.setDisable();
		finish();
	}
	@Override
	public void bluetoothStateConnectionChanged(boolean isConnected,String message) {
		if(isConnected){
			app.getSync().setSyncStateChangedListener(this);
		}
		else{
			if(bt.isEnabled()){
				bt.setDisable();
			}
			setButtonsWhenBtEnabled();
			app.getFacebook().resetDataCompetitor();
			competitorProfilePicture.setVisibility(View.GONE);
		}
		showToast(message);
		devicesNamesAdapter.clear();	
	}
	@Override
	public void bluetoothStateChanged(int state) {
		super.bluetoothStateChanged(state);
		switch (state) {
		case BluetoothAdapter.STATE_OFF:
			// show message bluetooth has disable and change buttons
			showToast("bluetooth turn off");
			setButtonsWhenBtDisabled();
			break;

		case BluetoothAdapter.STATE_ON:
        	// show message bluetooth has enable and change buttons
			showToast("bluetooth turn on");
			setButtonsWhenBtEnabled();
			break;
		}
	}
	// Create a BroadcastReceiver

	private final BroadcastReceiver ReceiverScanDeviceBluetooth = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
		    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
		    	// the bluetooth found other device
		        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
		        // add the device to list of devices
		        devicesList.add(device);
		        // show the device found on activity
		        devicesNamesAdapter.add(device.getName() + "\n" + device.getAddress());
		        lv.setAdapter(devicesNamesAdapter);
		    }
		    else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
		    	showToast("scan has started");
		    }
		    else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
		    	showToast("scan has finished");
		    }
		    
		}
		
	};
	private void setButtonsWhenBtEnabled(){
		butScan.setEnabled(true);
		butBT.setBackgroundDrawable(
				getResources().getDrawable(R.drawable.bluetooth_off));
		
	}
	private void setButtonsWhenBtDisabled(){
		butScan.setEnabled(false);
		butBT.setBackgroundDrawable(
				getResources().getDrawable(R.drawable.bluetooth_on));
		devicesList.clear();
		devicesNamesAdapter.clear();
	}
	public void startedSync() {
		showToast("Syncing your partner\'s device");
	}	
	public void finishedSync() {
		showToast("sync has finished");
		// the sync is over the application move to next stage
		// (application move to selectGameActivity)
		MyFacebook fb = app.getFacebook();
		
		buildProfilePicture(competitorProfilePicture,fb.getCompetitorUserId());
		fb.setCompetitorProfilePictureView(competitorProfilePicture);
		
		Drawable drawable = MyFacebook.convertToDrawable(this, competitorProfilePicture);
		fb.setCompetitorProfilePicture(drawable);
		
		Intent iSelectGameActivity = new Intent(MainActivity.this,SelectGameActivity.class);
		startActivity(iSelectGameActivity);
	}
	private void buildProfilePicture(ProfilePictureView profilePicture,String userId){
		profilePicture.setProfileId(userId);
		profilePicture.setPresetSize(ProfilePictureView.SMALL);
		profilePicture.setVisibility(View.VISIBLE);
	}
	public void facebookOpenSession(boolean isSuccess, String exception) {
		if(isSuccess){
			MyFacebook fb =app.getFacebook(); 
			tvUserName.setVisibility(View.VISIBLE);
			tvUserName.setText("welcome " + fb.getUser().getName());
			
			buildProfilePicture(myProfilePicture,fb.getUser().getId());
			
			Drawable d = MyFacebook.convertToDrawable(this, myProfilePicture);
			fb.setMyProfilePicture(d);
			fb.setMyUserId(fb.getUser().getId());
			fb.setMyUserName(fb.getUser().getUsername());
			fb.setMyProfilePictureView(myProfilePicture);
		}
		else{
			showToast(exception);
			facebookCloseSession();
		}
	}
	@Override
	public void facebookCloseSession() {
		tvUserName.setText("");
		tvUserName.setVisibility(View.GONE);
		myProfilePicture.setVisibility(View.GONE);
	}
}